import {Component, OnInit} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute} from "@angular/router";
import {Location} from "@angular/common";
import {StarService} from "../star.service";
import {Page} from "../../../public/util/page";
import {Setting} from '../../../public/setting/setting';

@Component({
  selector: 'app-star-level-rule-edit',
  templateUrl: './star-level-rule-edit.component.html',
  styleUrls: ['./star-level-rule-edit.component.css']
})
export class StarLevelRuleEditComponent implements OnInit {
  public isConfirmLoading: boolean = false;
  public id: string; //starLevelRule
  public validateForm: FormGroup;//企业登录的表单
  public starLevelList:Array<any> = [];//星级列表
  public msgTip = Setting.msgTip;

  constructor(private fb: FormBuilder, private starService: StarService, private route: ActivatedRoute, public location: Location) {
    this.validateForm = this.fb.group({
      starLevelCode: [null, Validators.compose([Validators.required])], // 星级编码
      level: [null, Validators.compose([Validators.required])], // 层级
      rate: [null, Validators.compose([Validators.required])] // 动态奖励百分比
    });
  }

  ngOnInit() {
    this.getStarLevelList();//获取星级列表
    this.route.url.subscribe(url => {
      const curPath = url[0].path;
      if (curPath === 'modify') {
        this.id = this.route.snapshot.params.id;//获取参数
        this.loadStarLevelRuleInfo();
      }//修改前查询出供应商信息
    })
  }

  getStarLevelList(){
    this.starService.getStarLevelList({curPage:1,pageSize:100}).then((res:Page) => {
      if(res && res.voList) this.starLevelList = res.voList;
    })
  }

  /**
   * 表单确认
   */
  addStarLevelRule($event) {
    $event.preventDefault();
    //1.进行脏检查，提示未填的必填字段
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.isConfirmLoading = true;
    let formData = Object.assign({},this.validateForm.value);
    //添加starLevelRule
    if (this.id) {
      formData.id = this.id;
      this.starService.modifyStarLevelRule(formData).then((data: any) => {
        this.isConfirmLoading = false;
        this.validateForm.reset();
        this.location.back();
      }).catch(res => this.isConfirmLoading = false)
    } else {
      this.starService.addStarLevelRule(formData).then((data: any) => {
        this.isConfirmLoading = false;
        this.location.back();
      }).catch(res => this.isConfirmLoading = false)
    }
  }

  /**
   * 查询starLevelRule信息
   */
  loadStarLevelRuleInfo() {
    this.starService.loadStarLevelRule(this.id).then((data: any) => {
      this.validateForm.patchValue(data);
    })
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }
}
